package com.wowangz.cms.systemmanage.userduty.api;

import java.io.IOException;
import java.rmi.server.ServerCloneException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.duty.pojo.Duty;
import com.wowangz.cms.systemmanage.userduty.dto.UserDutyCheckDto;
import com.wowangz.cms.systemmanage.userduty.dto.UserDutyDto;
import com.wowangz.cms.systemmanage.userduty.pojo.UserDuty;
import com.wowangz.cms.systemmanage.userduty.service.UserDutyService;
import com.wowangz.cms.user.pojo.User;
import com.wowangz.cms.user.service.UserService;

/**
 * 用户职责
 *
 * @author cakohy
 *
 */
@Controller
@Scope("prototype")
public class UserDutyController extends BaseController {

	/**
	 * 获得的列表的页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/user/list.web", method = RequestMethod.GET)
	public String list(Model model) {
		
		return "/WEB-INF/jsp/systemmanage/userduty/list";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/systemmanage/userDuty/user/getUserListJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getUserListJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			Object object = map.get("poststatus");
			if (object != null && StringUtils.equals(object.toString(), "0")) {
				map.remove("poststatus");
			}
			DataResult dataResult = getDataResult(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获得一个 DataResult对象
	 *
	 * @param pangingParam
	 * @param map
	 * @return
	 * @throws ServerCloneException
	 */
	private DataResult getDataResult(HttpServletRequest request, PangingParam pangingParam, Map<String, Object> map)
			throws ServerCloneException {
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		map.put("statusid", SysConstant.YesOrNo.YES);
		long resultCount = userDutyService.queryUserCountByMap(map);
		List<UserDutyDto> resultList = userDutyService.queryUserPageByMap(map);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultCount);
		dataStyle.setDataList(resultList);
		dataStyle.addDepict("userno", DataTypeConstant.STRING);
		dataStyle.addDepict("loginname", DataTypeConstant.STRING);
		dataStyle.addDepict("username", DataTypeConstant.STRING);
		dataStyle.addDepict("validstart", DataTypeConstant.DATE);
		dataStyle.addDepict("validend", DataTypeConstant.DATE);
		dataStyle.addDepictByFunction("poststatus", SysConstant.Relevance.class, "getName", new Class[] { long.class });
		dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });
		dataStyle.addDepict("id", DataTypeConstant.LONG);
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}
	
	/**
	 * 打开职责设置页面
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/user/toDutyList.web", method = RequestMethod.GET)
	public String toDutyList(HttpServletRequest request, HttpServletResponse response, Model model) {
		UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		String userid = request.getParameter("id");
		System.out.println("用户id：" + userid);
		if (StringUtils.isNotEmpty(userid)) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", Long.parseLong(userid));
			User user = userService.findUserById(userid);
			model.addAttribute("user", user);
			
			List<UserDuty> list = userDutyService.queryUserPostByUserid(Long.parseLong(userid));
			String idList = "";
			if (list != null && list.size() > 0) {
				for (Iterator<UserDuty> iterator = list.iterator(); iterator.hasNext();) {
					UserDuty userDuty = iterator.next();
					idList += userDuty.getDutyid() + ",";
				}
			}
			model.addAttribute("idList", StringUtils.isNotEmpty(idList) ? idList.substring(0, idList.length() - 1) : "");

		}
		return "/WEB-INF/jsp/systemmanage/userduty/dutyList";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/systemmanage/userDuty/user/getUserDutyListJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getUserDutyListJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", "modifytime");
			map.put("order", "desc");
			DataResult dataResult = getUserDutyList(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private DataResult getUserDutyList(HttpServletRequest request, PangingParam pangingParam, Map<String, Object> map) {
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		map.put("statusid", SysConstant.RecordStatus.VALID);
		List<Duty> resultList = userDutyService.queryDutyListByMap(map);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultList.size());
		dataStyle.setDataList(resultList);
		dataStyle.addDepict("dutyid", DataTypeConstant.LONG);
		dataStyle.addDepict("dutycode", DataTypeConstant.STRING);
		dataStyle.addDepict("dutyname", DataTypeConstant.STRING);
		dataStyle.addDepictByFunction("dutycheckstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}
	

	/**
	 *
	 * @描述：保存职责
	 * @author HUANGYUAN
	 * @TIME:2015年8月31日 上午10:52:28
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/userDuty/user/insert.web", method = { RequestMethod.POST, RequestMethod.GET })
	public void insert(HttpServletRequest request, HttpServletResponse response, Model model) {
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
		String userid = request.getParameter("userid");
		String dutyids = request.getParameter("dutyids");
		Map<String, Object> messageMap = new HashMap<String, Object>();
		try {
			String idList = "";
			if (StringUtils.isNotEmpty(userid)) {
				userDutyService.delete(Long.parseLong(userid));
				String[] ids = dutyids.split(",");
				if (StringUtils.isNotEmpty(dutyids) && ids.length > 0) {
					for (String dutyid : ids) {
						UserDuty userDuty = new UserDuty();
						userDuty.setDutyid(Long.parseLong(dutyid));
						userDuty.setUserid(Long.parseLong(userid));
						userDuty.setCheckstatus(SysConstant.CheckStatus.SAVE);
						userDuty.setStatusid(SysConstant.RecordStatus.VALID);
						userDuty.setInputuserid(getUserContext().getLoginUser().getId());
						userDuty.setInputtime(new Date());
						userDuty.setModifyuserid(getUserContext().getLoginUser().getId());
						userDuty.setModifytime(new Date());
						userDutyService.insert(userDuty);
					}
				}
				User user = userService.findUserById(userid);
				model.addAttribute("user", user);
				messageMap.put("result", "success");
				model.addAttribute("idList", StringUtils.isNotEmpty(idList) ? idList.substring(0, idList.length() - 1) : "");
			}
		} catch (ServiceException e) {
			messageMap.put("result", "error");
			e.printStackTrace();
		} catch (NumberFormatException e) {
			messageMap.put("result", "error");
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(messageMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 点击菜单"用户与岗位关联复核"显示“"用户与岗位关联复核”列表
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/user/checkList.web")
	public String queryCheckList(HttpServletRequest request, HttpServletResponse response, Model model) {

		return "/WEB-INF/jsp/systemmanage/userduty/checkList";
	}
	
	/**
	 * 打开“用户与岗位关联复核”列表加载列表数据
	 *
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/systemmanage/userDuty/queryCheckListInfoDataGrid.json")
	public void queryCheckListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			map.put("checkstatus", SysConstant.CheckStatus.CHECKED);
			map.put("poststatus", SysConstant.CheckStatus.SAVE);
			map.put("modifyuserid", getUserContext().getLoginUser().getId());// 交叉复核必须条件

			UserDutyService userDutyService = (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
			long resultCount = userDutyService.findResultCount(map);
			List<UserDutyCheckDto> resultList = userDutyService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("userno", DataTypeConstant.STRING);
			dataStyle.addDepict("loginname", DataTypeConstant.STRING);
			dataStyle.addDepict("username", DataTypeConstant.STRING);
			dataStyle.addDepict("validstart", DataTypeConstant.DATE);
			dataStyle.addDepict("validend", DataTypeConstant.DATE);
			dataStyle.addDepictByFunction("poststatus", SysConstant.Relevance.class, "getName", new Class[] { long.class });
			dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 打开复核职责页面
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/user/toCheckDutyList.web", method = RequestMethod.GET)
	public String toCheckDutyList(HttpServletRequest request, HttpServletResponse response, Model model) {
		UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
		String userid = request.getParameter("userid");
		if (StringUtils.isNotEmpty(userid)) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", Long.parseLong(userid));
			User user = userService.findUserById(userid);
			model.addAttribute("user", user);

		}
		return "/WEB-INF/jsp/systemmanage/userduty/checkDutyList";
	}
	
	/**
	 * 点击单个复核数据加载职责列表数据
	 *
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/systemmanage/userDuty/queryCheckDutyListInfoDataGrid.json")
	public void queryCheckDutyListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		String userid = request.getParameter("userid");
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			map.put("checkstatus", SysConstant.CheckStatus.CHECKED);
			map.put("userid", userid);

			UserDutyService userDutyService = (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
			long resultCount = userDutyService.findDutyResultCount(map);
			List<Duty> resultList = userDutyService.findDutyResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("dutyid", DataTypeConstant.LONG);
			dataStyle.addDepict("dutycode", DataTypeConstant.STRING);
			dataStyle.addDepict("dutyname", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("dutycheckstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });

			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 单条复核
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/check.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void check(HttpServletRequest request, HttpServletResponse response, Model model) {
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		String userid = request.getParameter("userid");
		UserDuty userDuty = new UserDuty();
		try {
			if (StringUtils.isNotEmpty(userid) ) {
				userDuty.setUserid(Long.parseLong(userid));
				userDuty.setCheckstatus(SysConstant.CheckStatus.CHECKED);
				userDuty.setStatusid(SysConstant.RecordStatus.VALID);
				userDuty.setModifyuserid(getUserContext().getLoginUser().getId());
				userDuty.setModifytime(new Date());
				userDutyService.update(userDuty);
			}
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert8"));
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert9"));
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 多条复核
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/userDuty/checkMore.json", method = { RequestMethod.POST, RequestMethod.GET })
	public void checkMore(HttpServletRequest request, HttpServletResponse response, Model model) {
		UserDutyService userDutyService= (UserDutyService) IssTransactionContainer.getInstance(UserDutyService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		String useridss = request.getParameter("userids");// 根据userid进行多条复核
		try {
			if (StringUtils.isNotEmpty(useridss)) {
				String[] userids = useridss.split(",");
				if (userids.length > 0) {
					for (String userid : userids) {
						UserDuty userDuty = new UserDuty();
						userDuty.setUserid(Long.parseLong(userid));
						userDuty.setCheckstatus(SysConstant.CheckStatus.CHECKED);
						userDuty.setStatusid(SysConstant.RecordStatus.VALID);
						userDuty.setModifyuserid(getUserContext().getLoginUser().getId());
						userDuty.setModifytime(new Date());
						userDutyService.update(userDuty);
					}
				}
			}
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert8"));
		} catch (Exception e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert9"));
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
